import {
	observable,
	action,
	computed,
	toJS,
} from 'mobx';
import {
	Tools,
	Bubble,
	Modal,
} from "weaver-mobile";
import {
	Form
} from 'weaver-mobile-page';
import * as api from '../../apis/forgetPassword';
import {
  checkWeakPass
} from "../../util/PASSUtil.js";
const getLabel = Tools.getLabel;
const alert = Modal.alert;

class ForgetPasswordStore {
	@observable count = 60;

	@action
	countDown = () => {
		this.count--;
	}
	//-----------------步骤-------------------
	steps = 3;

	//当前步骤
	@observable current = 0;

	//下一步
	@action increase = () => {
		this.current++;
	}

	//上一步
	@action decrease = () => {
		this.current--;
	}

	//-----------------副标题-------------------
	@computed get subTitle() {
		let title;
		switch (this.current) {
			case 0:
				title = getLabel(511062, '选择找回方式');
				break;
			case 1:
				title = getLabel(15357, '验证');
				break;
			case 2:
				title = getLabel(517848, '重设密码');
				break;
		}

		return title;
	}

	//-----------------表单-------------------
	@observable form = new Form.Store();
	@observable date = new Date();

	//初始化表单
	@action getForm = () => {
		const params = this.paramsCollector;
		if (this.languageId) {
			Object.assign(params,{
				languageId:this.languageId
			});
		}
		api[this.formApiName](params).then(data => {
			const {
				status,
				conditions
			} = data;

			if (status === '1') {
				this.form.initForm(conditions);

				(this.current === 2) && this.extractPwdStrengthRule(conditions);
			} else {
				Bubble.error();
			}

		}, error => {});
	}

	//抽取密码强度相关规则
	extractPwdStrengthRule = (conditions) => {
		conditions.map(c => {
			c.items.map(item => {
				const {
					domkey
				} = item;

				if (domkey[0] === 'newpswd') {
					Object.assign(this.pwdStrengthRelated, item.otherParams);
				}
			});
		});
	}

	//获取当前表单元素的键值对
	@computed get formParams() {
		const {
			dataToParams,
			formData
		} = this.form;

		return dataToParams(formData);
	}

	//获取当前表单接口名称
	@computed get formApiName() {
		const {
			type
		} = this.paramsCollector;

		let name;

		switch (this.current) {
			case 0:
				name = 'getForgotPasswordForm'
				break;
			case 1:
				if (type === 'phoneCode') {
					name = 'confirmPhoneCodeForm'
				}
				if (type === '-1') {
					name = 'passwordQuestionForm'
				}
				if (type === 'emailCode') {
					name = 'confirmEmailCodeForm'
				}
				break;
			case 2:
				name = 'resetPasswordForm'
				break;
		}

		return name;
	}

	paramsCollector = {
		// languageId: 7 //暂时写死
	}

	setLanguageId = (languageId) => {
		this.languageId = languageId;
	}

	//收集参数
	collectParams = (id) => {
		if (id) {
			Object.assign(this.paramsCollector, {
				id
			});
		} else {
			Object.assign(this.paramsCollector, {
				...this.formParams
			});
		}
	}

	//强制刷新验证码
	@action forceRefreshVerifyCode = () => {
		this.date = new Date();
	}

	//-----------------校验表单------------------
	@observable reCountDown = true; //触发倒计时

	@action forceCountDown = () => {
		this.reCountDown = !this.reCountDown;
	}

	//点击【下一步】触发的调用链。
	//首先判断【找回方式】是否设置并开启
	//判断成功，则发送验证消息
	firstStepClickChain = () => this.preCheck({
		success: () => this.sendMsg({
			success: (data) => {
				const{forgotpasswordExpiration}=data;
				if (forgotpasswordExpiration) {
					this.count = forgotpasswordExpiration
				}
				['increase', 'showCodeSentMsg', 'getForm'].forEach(f => {
					this[f](data);
				})
			}
		})
	});

	//消息发送后的提示信息
	showCodeSentMsg = (data) => {
		const {
			status,
			id
		} = data;

		const {
			type
		} = this.paramsCollector;

		if (status !== '1') return;

		if (type === 'phoneCode') {
			Bubble.remind(`${getLabel(511063,'手机验证码已发送到手机')} ${id}, ${getLabel(125973,'请注意查收！')}`);
		}

		if (type === 'emailCode') {
			Bubble.remind(`${getLabel(511064,'邮件验证码已发送到邮箱')} ${id}, ${getLabel(125973,'请注意查收！')}`);
		}
	}

	//点击【验证】，触发的调用链。
	//主要动作：验证表单信息。
	secondStepClickChain = () => this.validate({
		success: () => {
			this.increase();
			this.getForm();
		}
	})

	//点击【保存】，触发的调用链。
	thirdStepClickChain = () => {
		this.saveNewPassword();
	}

	//观察密码强度相关参数
	@observable pwdStrengthRelated = {
		minpasslen: 1,
		passwordComplexity: '0',
		passwordStrength: true,
	}

	//前端校验，包括必填项校验、表单域是否相等校验等。
	preValidate = () => {
		const {
			validatecode,
			loginid,
			answer,
			newpswd,
			cfmpswd,
			phoneCode,
			emailCode,
		} = this.formParams;

		const {
			type
		} = this.paramsCollector;

		//不同步骤，检验失败的情况。
		const bl1 = (this.current === 0) && (!type || !loginid),
			bl2 = (this.current === 1) && (type === '-1' ? !answer : (type === 'phoneCode') ? !phoneCode : !emailCode),
			bl3 = (this.current === 2) && (!newpswd || !cfmpswd || !this.isEqual(newpswd, cfmpswd) || !this.isPassminlen(newpswd) || !this.isMatchRule(newpswd));

		if ((bl1 || bl2 || bl3) || !validatecode) {
			this.forceRefreshVerifyCode();
		}

		switch (this.current) {
			case 0:
				if (!type) {
					Bubble.error(getLabel(511070, '请选择找回方式！'));
					return false;
				}
				if (!loginid) {
					Bubble.error(getLabel(511065, '请输入账号！'));
					return false;
				}
				break;
			case 1:
				if (type === 'phoneCode' && !phoneCode) {
					Bubble.error(getLabel(517862, '请输入手机验证码！'));
					return false;
				}
				if (type === '-1' && !answer) {
					Bubble.error(getLabel(511066, '请填写密保问题答案！'));
					return false;
				}
				if (type === 'emailCode' && !emailCode) {
					Bubble.error(getLabel(511067, '请输入邮件验证码！'));
					return false;
				}
				break;
			case 2:
				if (!newpswd) {
					Bubble.error(getLabel(511068, '请填写新密码！'));
					return false;
				}
				if (!cfmpswd) {
					Bubble.error(getLabel(511069, '请确认新密码！'));
					return false;
				}
				if (!this.isEqual(newpswd, cfmpswd)) {
					return false;
				}
				if (!this.isPassminlen(newpswd)) {
					return false;
				}
				if (!this.isMatchRule(newpswd)) {
					return false;
				}
				break;
		}
		if (!validatecode) {
			Bubble.error(getLabel(517861, '请输入验证码！'));
			return false;
		}

		return true;
	}

	//判断【新密码】和【确认密码】是否相等
	isEqual = (newPwd, confirmPwd) => {
		if (newPwd === confirmPwd) {
			return true;
		} else {
			Bubble.error(getLabel(504376, '密码确认不正确!'));
			return false;
		}
	}

	//判断密码是否符合最小长度
	isPassminlen = (newPwd) => {
		if (newPwd.length < this.pwdStrengthRelated.minpasslen) {
			Bubble.error(`${getLabel('20172', "密码长度不能小于")}${this.pwdStrengthRelated.minpasslen}`);
			return false;
		} else {
			return true;
		}
	}

	//判断密码是否符合密码复杂度
	isMatchRule = (newPwd) => {
		const judge = (regExps) => {
			return regExps.every(regExp => regExp.test(newPwd))
		}
		if (this.pwdStrengthRelated.passwordComplexity == '1') {
			const regExps = [/[a-z]+/, /[A-Z]+/, /\d+/];
			if (!judge(regExps)) {
				Bubble.error(getLabel('514130',"新密码不符合要求，必须包含字母大写、字母小写、数字！请重新输入！"));
				return false;
			}
		}
		if (this.pwdStrengthRelated.passwordComplexity == '2') {
			const regExps = [/[a-zA-Z_]+/, /\W+/, /\d+/];
			if (!judge(regExps)) {
				Bubble.error(getLabel('514057',"新密码不符合要求，必须包含字母、数字、特殊字符！请重新输入！"));
				return false;
			}
		}
		if (this.pwdStrengthRelated.passwordComplexity == '3') {
			const regExps = [/[a-zA-Z_]+/, /\d+/];
			if (!judge(regExps)) {
				Bubble.error(getLabel('514131', "新密码不符合要求，必须包含字母、数字！请重新输入！"));
				return false;
			}
		}
		if (this.pwdStrengthRelated.passwordComplexity == "4") {
             const regExps = [/[a-z]+/, /[A-Z]+/,/\d+/,/\W+/];
             if (!judge(regExps)) {
             	Bubble.error(getLabel(521798, "新密码不符合要求，必须为字母大写、字母小写、数字、特殊字符组合！请重新输入！"));
                return false;
            }
        }

		return true;
	}

	//判断【找回方式】是否设置和开启
	preCheck = (config) => {
		const {
			success
		} = config;

		if (!this.preValidate()) return;
		const params = this.paramsCollector;
		if (this.languageId) {
			Object.assign(params,{
				languageId:this.languageId
			});
		};
		api.forgotPasswordCheckMsg(params).then(data => {
			const {
				status,
				message,
				id,
			} = data;

			if (status === '1') {
				this.collectParams(id);
				success(id)
			} else {
				alert(message, '', [{
					text: getLabel(826, '确定'),
					onPress: () => this.forceRefreshVerifyCode(),
				}])
			}
		}, error => {});
	}

	//发送验证信息
	sendMsg = (config) => {
		const {
			success
		} = config;
		const params = this.paramsCollector;
		if (this.languageId) {
			Object.assign(params,{
				languageId:this.languageId
			});
		};
		api.forgotPasswordToNext(params).then(data => {
			const {
				status,
				message,
			} = data;

			if (status === '1') {
				success(data);
			} else {
				alert(message, '', [{
					text: getLabel(826, '确定'),
					onPress: () => {},
				}])
			}

			this.forceRefreshVerifyCode()

		}, error => {});
	}

	//获取验证接口的名称
	@computed get validateApiName() {
		const {
			type
		} = this.paramsCollector;

		let name;
		switch (type) {
			case 'phoneCode':
				name = 'confirmPhoneCodeToNext';
				break;
			case '-1':
				name = 'passwordQuestionToNext';
				break;
			case 'emailCode':
				name = 'confirmEmailCodeToNext';
				break;
		}

		return name;
	}

	//验证
	validate = (config) => {
		const {
			success
		} = config;

		if (!this.preValidate()) return;
		const params = this.paramsCollector;
		if (this.languageId) {
			Object.assign(params,{
				languageId:this.languageId
			});
		};
		api[this.validateApiName](params).then(data => {
			const {
				status,
				message,
			} = data;

			if (status === '1') {
				success();
			} else {
				Bubble.error(message);
			}
			this.forceRefreshVerifyCode();
		}, error => {});
	}

	//保存新密码
	saveNewPassword = () => {
		if (!this.preValidate()) return;

		checkWeakPass(this.paramsCollector.newpswd,() =>{
			const params = this.paramsCollector;
			if (this.languageId) {
				Object.assign(params,{
					languageId:this.languageId
				});
			};
			api.saveResetPassword(params).then(data => {
				const {
					status,
					message,
				} = data;

				if (status === '1') {
					Bubble.success(message || getLabel(383312, '修改成功'));
					window.setTimeout(() => {
						window.em && window.em.checkJsApi('pushToLogin') && window.em.pushToLogin()
					}, 1000);
				} else {
					Bubble.error(message);
					this.forceRefreshVerifyCode();
				}

			}, error => {});
		},()=>{
			this.forceRefreshVerifyCode();
		});
	}

	//回退到上一步
	@action goBack = () => {
		this.decrease();
		this.getForm();
	}

	//重复发送
	repeatSend = () => {
		const {
			validatecode
		} = this.formParams;

		if (!validatecode) {
			Bubble.error(getLabel(517861, '请输入验证码！'));
			return;
		}

		Object.assign(this.paramsCollector, {
			validatecode
		});

		this.sendMsg({
			success: (data) => {
				const{forgotpasswordExpiration}=data;
				if (forgotpasswordExpiration) {
					this.count = forgotpasswordExpiration
				}
				this.showCodeSentMsg(data);
				this.forceCountDown();
			}
		});

	}

	//-----------------底部按钮-------------------
	@computed get buttonTitle() {
		let title;
		switch (this.current) {
			case 0:
				title = getLabel(504372, '下一步');
				break;
			case 1:
				title = getLabel(15357, '验证');
				break;
			case 2:
				title = getLabel(86, '保存');
				break;
		}

		return title;
	}
}

export const forgetPasswordStore = new ForgetPasswordStore();